<?php

/*
 * @name: 公共函数库
 * @Description: 保存所有公共函数方法
 * @Author: longdada
.* @ LastEditors: longdada
 * @Date: 2019-02-23 14:18:14
.* @ LastEditTime: 2019-03-28 19:49:17
 */
/* name:获取随机字符串函数
 * purpose: 按照不同的场景定义不同的验证规则更加灵活 
 * param1: 获取随机字符串随机内容的开始位置
 * param2: 获取随机字符串随机内容的结束位置
 * param3: 获取随机字符串的长度
 * return:  无
 * author:longdada
 */
// 应用公共文件
function showMyName($name){
    return '这个名字是'+$name;
}
function generate_random_str($start=0,$end=54,$str_len=16){
	$base_arr=[
			'1','a','b','c','d','e','f','g','h','j',
			'k','m','n','p','q','r','s','t','u','w',
			'x','y','z','A','B','C','D','E','F','G',
			'H','J','K','L','M','N','P','Q','R','S',
			'T','U','W','X','Y','Z','0','1','2','3',
			'4','5','6','7','8','9'];
	$rs_str='';
	for($i=0;$i<$str_len;$i++){
		$key=rand($start, $end);
		$rs_str.=$base_arr[$key];	
	}
	return $rs_str;
}
/* name:生成密码密文
 * purpose: 获取一个随机字符串对原密码进行加密
 * param1: 源密码
 * return:  生成的密码密文和随机字符串
 * author:longdada
 * write_time:2019/01/22 22:36
 */
function generate_passwd($pass){
	$rand_str=generate_random_str(0,54,6);
	$rs_arr['pass']=md5("**&%^%@!".md5($pass).$rand_str);
	$rs_arr['pass_code']=$rand_str;
	return $rs_arr;
}
/* name:生成比对密文
 * purpose: 用用户输入的密码和数据库存储的密码随机字符串重新生成密文 并返回用于比对
 * param1: 客户录入的密码 
 * param2: 生成密码时附加的随机字符串
 * return:  返回输入密码生成的密文 
 * author:longdada
 * write_time:2019/01/22 22:36
 */
function diff_passwd($pass,$code){
	$rs_arr=md5("**&%^%@!".md5($pass).$code);
	return $rs_arr;
}
function get_region_name($id){
	$name = db('region') -> where('region_id',$id) -> value('region_name');
	return $name;
}

/* 
 * @name 上传图片---多图
 * @purpose 文件对象形式图片上传
 * @param 图片对象 
 * @return 返回上传后保存的路径
 */
function upload_goods_file_object($files){
	$upload_url='./static/uploads/'. date("Ym")."/";
	$img_url = array();
	foreach ($files as $file) {
		if(!is_dir($upload_url))mkdir($upload_url,0777,true);
		chmod($upload_url,0777);
		$file_name=date("YmdHis").generate_random_str(3,52,8);
		$info=$file->move($upload_url,$file_name);
		$rs_url=str_replace("./", "/", $upload_url).$info->getSaveName();
		chmod(".".$rs_url,0777);
		$img_url[] = $rs_url;
	}
	return  $img_url;
}
/**
 * 格式化字节大小
 * @param  number $size 字节数
 * @param  string $delimiter 数字和单位分隔符
 * @return string            格式化后的带单位的大小
 */
function format_bytes($size, $delimiter = '') {
    $units = array('B', 'KB', 'MB', 'GB', 'TB', 'PB');
    for ($i = 0; $size >= 1024 && $i < 5; $i++) $size /= 1024;
    return round($size, 2) . $delimiter . $units[$i];
}


//插入订单操作记录
function order_action($name,$order_id,$order_status,$pay_status,$shipping_status,$note=''){
	$data = array(
		'order_id'=>$order_id,
		'action_user'=>$name,
		'order_status'=>$order_status,
		'pay_status'=>$pay_status,
		'shipping_status'=>$shipping_status,
		'action_note'=>$note,
		'log_time'=>time()
		);
	db('order_action')->insert($data);    
}
//插入支付记录
function insert_pay_log($order_id,$order_amount,$order_type=0){
	$pay_log = array(
		'order_id'=>$order_id,
		'order_amount'=>$order_amount,
		'order_type'=>$order_type
		);
	$log_id = db('pay_log')->insertGetid($pay_log);
	return $log_id;
}

/**
 * 插入用户消息
 */
function insert_user_msg($user_id,$content,$title=''){
	$data = array(
		'title'=>$title,
		'content'=>$content,
		'add_time'=>time(),
		'type'=>1
		);
	$msg_id = db('msg')->insertGetid($data);
	$data = array(
		'user_id'=>$user_id,
		'msg_id'=>$msg_id,
		'add_time'=>time(),
		);
	db('user_msg')->insertGetid($data);
}


/**
 * 记录帐户变动
 * @param   int     $user_id        用户id
 * @param   float   $user_money     可用余额变动
 * @param   float   $frozen_money   冻结余额变动
 * @param   int     $pay_points     消费积分变动
 * @param   string  $change_desc    变动说明
 * @param   int     $change_type    变动类型：参见常量文件
 * @return  void
 */
function log_account_change($user_id, $user_money = 0,  $pay_points = 0,$title='', $change_desc = '', $change_type = 0)
{
	$user_info = db('user')->where('id',$user_id)->field('user_money,score')->find();
	$time = time();
	if ($user_money!=0) {
		$type = 1;
		$data = array(
			'user_id'=>$user_id,
			'type'=>$type,
			'change_money'=>abs($user_money),
			'change_type'=>$change_type,
			'money'=>$user_info['user_money'],
			'next_money'=>$user_info['user_money'] + $user_money,
			'title'=>$title,
			'remark'=>$change_desc,
			'add_time'=>$time,
			'update_time'=>$time
			);
		db('user_change')->insert($data);
		db('user')->where('id',$user_id)->exp('user_money',"user_money+$user_money")->update();
	}
	if ($pay_points!=0) {
		$type = 2;
		$data = array(
			'user_id'=>$user_id,
			'type'=>$type,
			'change_money'=>abs($pay_points),
			'change_type'=>$change_type,
			'money'=>$user_info['score'],
			'next_money'=>$user_info['score'] + $pay_points,
			'title'=>$title,
			'remark'=>$change_desc,
			'add_time'=>$time,
			'update_time'=>$time
			);
		db('user_change')->insert($data);
		db('user')->where('id',$user_id)->exp('score',"score+$pay_points")->update();
	}
	
}

/**
 * author:york  2019/5/14 14:23
 * name:获取资金类型
 */
function getWashType($type){
    $moneyType = config('money_type');
    return isset($moneyType[$type])?$moneyType[$type]:'';
}

/**
 * author:york  2019/5/14 14:25
 * name:
 */
function getChangeType($type){
    $changeType=config('change_type');
    return isset($changeType[$type])?$changeType[$type]:'';
}



/* name:获取token
 * purpose: 获取请求头中的用户凭证
 * return:  返回获取的值 
 * author:longdada
 * write_time:2019/01/22 22:36
 */
function get_token(){
	return request()->header('TOKEN');
}
/* name:获取user_token
 * purpose: 获取请求头中的用户凭证
 * return:  返回获取的值 
 * author:longdada
 * write_time:2019/01/22 22:36
 */
function get_user_token(){
	return request()->header('USERTOKEN');
}
/* name:上传图片
 * purpose: 文件对象形式图片上传
 * param1: 图片对象 
 * return:  返回上传后保存的路径
 * author:longdada
 * write_time:2019/01/31 14:36
 */
function upload_file_object($file){
	// echo "1";
	$upload_url='./static/uploads/'. date("Ym")."/";
	// echo "2";
	if(!is_dir($upload_url))mkdir($upload_url,0777,true);
	// echo "3";
	chmod($upload_url,0777);
	// echo "4";
	$file_name=date("YmdHis").generate_random_str(3,52,8);
	// echo "5";
	$info=$file->move($upload_url,$file_name);
	if($info){
		// echo "6";
		$rs_url=str_replace("./", "/", $upload_url).$info->getSaveName();
		// echo "7";
		chmod(".".$rs_url,0777);
		// echo "8";
		return  $rs_url;
	}else{
		return $file->getError();
	}
}
/* name:上传图片
 * purpose: BASE64形式图片上传
 * param1: base64 图片数据 
 * return:  返回上传后保存的路径
 * author:longdada
 * write_time:2019/02/02 7:45
 */
function upload_file_base64($base64_data){
	//file_put_contents("post_data.txt",json_encode($base64_data,JSON_UNESCAPED_UNICODE).PHP_EOL,FILE_APPEND);
	$base64=$base64_data;
	$base64_image = str_replace(' ', '+', $base64);
	//post的数据里面，加号会被替换为空格，需要重新替换回来，如果不是post的数据，则注释掉这一行
	preg_match('/^(data:\s*image\/(\w+);base64,)/', $base64_image, $result);
	$file_name=date("YmdHis").generate_random_str(3,52,8).'.'.$result[2];
	$upload_url='./static/uploads/'. date("Ym")."/";
	if(!is_dir($upload_url))mkdir($upload_url,0777,true);
	//服务器文件存储路径
	file_put_contents($upload_url.$file_name, base64_decode(str_replace($result[1], '', $base64_image)));
	return str_replace('./', '/', $upload_url.$file_name);
}
/* name:上传图片---多图
 * purpose: 文件对象形式图片上传
 * param1: 图片对象 
 * return:  返回上传后保存的路径
 * author: 冲哥Carry
 * write_time:2019/02/15 14:36
 */
function filesUpload($files){
	$upload_url='./static/uploads/'. date("Ym")."/";
	$img_url = array();
	foreach ($files as $file) {
		if(!is_dir($upload_url))mkdir($upload_url,0777,true);
		chmod($upload_url,0777);
		$file_name=date("YmdHis").generate_random_str(3,52,8);
		$info=$file->move($upload_url,$file_name);
		$rs_url=str_replace("./", "/", $upload_url).$info->getSaveName();
		chmod(".".$rs_url,0777);
		$img_url[] = $rs_url;
	}
	return  $img_url;
}
/* name:上传图片
 * purpose: 文件对象形式图片上传
 * param1: 原图的url 
 * param2: 缩略图最大宽度 
 * param3: 缩略图最大高度
 * param3: 是否覆盖原图
 * return:  返回上传后保存的路径
 * author:longdada
 * write_time:2019/01/31 16:36
 */
function image_thumb($img_url,$width=600,$height=600,$is_cover=true){
	//  return '.'.$img_url;
	ini_set('memory_limit', '512M');
	// return ROOT_PATH.$img_url
	$image = \think\Image::open(".".$img_url);
	if($is_cover){
		$image->thumb($width,$height,1)->save('.'.$img_url); 
		$rs_url=$img_url;//覆盖原图
	}else{
		$upload_url='./static/uploads/'. date("Ym")."/";
		chmod($upload_url,0777);
		if(!is_dir($upload_url))mkdir($upload_url,0777,true);
		$file_name=date("YmdHis").generate_random_str(3,52,6).".".$image->type();
		$save_push=$upload_url.$file_name;
		$image->thumb($width,$height,1)->save($save_push); 
		$t_url=str_replace("./", "/", $save_push);
		$rs_url['s_url']=$img_url;//返回的原图地址
		$rs_url['t_url']=$t_url;//返回的缩略图地址
	}
	return $rs_url;
}
/**
 *生成分级树
 * @access public
 * @param  array $array 待分级数组
 * @param  string $str 基本html代码
 * @return string $rs_tree  返回生成的html代码
 * @throws Exception
 */
function generate_tree($array,$str){
	$tree = new \categoryTree\Tree();
	$tree->init($array);
	$rs_tree = $tree->get_tree(0, $str);
	return $rs_tree;
}
/**
 *查询所有的国家
 * @access public
 * @return string $rs_tree  返回生成的国家名称及logo
 * @throws Exception
 */
function get_country(){
	$country = db('country') -> field('con_name,img') -> select();
	return $country;
}
 /**
 *根据key获取对应的配置参数
 * @access public
 * @param  string $key 配置的key
 * @return string   配置的内容
 * @throws Exception
 */
function get_conf($key)
{
	if(!is_string($key) || empty($key)){
		return false;
	}
	$key=strtolower($key);
	$get_where['conf_key']=$key;
	return model('logic.system')->get_systrm_row($get_where);
}
/**
 *设置对应的配置参数
 * @access public
 * @param  string $key 配置的key
 * @return string   配置的内容
 * @throws Exception
 */
function set_conf($key,$data)
{
	if(!is_array($data) || empty($data) || !is_string($key) || empty($key)){
        return false;
    }
	$key=strtolower($key);
	return model('logic.system')->set_systrm_row($key,$data);
}

//订单付款
function order_paid($log_id,$total_fee){
	$pay_log = db('pay_log')->where('log_id',$log_id)->find();
	if($pay_log && $pay_log['is_paid'] == 0){
		// if($pay_log['order_amount'] != $total_fee){
		// 	return false;
		// }
		db('pay_log')->where('log_id',$log_id)->update(array('is_paid'=>1));
		//判断类型
		if($pay_log['order_type']==0){
			$order = db('order')->where("order_id=".$pay_log['order_id']." or parent_id=".$pay_log['order_id'])->field('user_id,order_id,order_amount,order_status,pay_status,shop_id,order_sn')->select();
			if(!$order){
				return false;
			}
			foreach ($order as $k => $v) {
				//修改订单状态为已付款
				db('order')->where('order_id',$v['order_id'])->update(array('pay_status'=>1,'order_status'=>1,'pay_time'=>time()));
				order_action('买家',$v['order_id'], 1, 1, 0, '确认付款');
				// get_bro($v['order_id'],$v['order_sn'],$v['user_id']);
			}
		}else if($pay_log['order_type']==2){
			//充值
			db('user_change')->where('id',$pay_log['order_id'])->update(['status'=>1]);
			$user_id = db('user_change')->where('id',$pay_log['order_id'])->value('user_id');
			db('user')->where('id',$user_id)->setInc('user_money',$pay_log['order_amount']);
		}
		
	}else{
		return false;
	}
	

}

//生成唯一邀请码
function get_code(){
	$code = 'abcdefghijklmnopqrstuvwxyz';
    $rand = $code[rand(0,25)]
        .strtoupper(dechex(date('m')))
        .date('d')
        .substr(time(),-5)
        .substr(microtime(),2,5)
        .sprintf('%02d',rand(0,99));
    for(
        $a = md5( $rand, true ),
        $s = '0123456789abcdefghijklmnopqrstuvwxyz',
        $d = '',
        $f = 0;
        $f < 6;
        $g = ord( $a[ $f ] ),
        $d .= $s[ ( $g ^ ord( $a[ $f + 8 ] ) ) - $g & 0x1F ],
        $f++
    );
    return $d;
}

function wdate($the_time) {
	$now_time = date ( "Y-m-d H:i:s", time () );
	$now_time = strtotime ( $now_time );
	$show_time = $the_time;
	$dur = $now_time - $show_time;
	if ($dur < 0) {
		return $the_time;
	} else {
		if ($dur < 60) {
			return $dur . '秒前';
		} else {
			if ($dur < 3600) {
				return floor ( $dur / 60 ) . '分钟前';
			} else {
				if ($dur < 86400) {
					return floor ( $dur / 3600 ) . '小时前';
				} else {
					if ($dur < 259200) { // 3天内
						return floor ( $dur / 86400 ) . '天前';
					} else {
						return date ( "m月d日", $the_time );
					}
				}
			}
		}
	}
}

/* name:检测用户的权限
 * purpose: 检测用户的权限
 * return:  
 * author: 冲哥Carry
 * write_time:2019/02/27 13:57
 */
function check_role($user_id){
    $check_role = array();
    //判断是否有用户登录
    if($user_id){//已登录
        //判断该用户是不是刀圈店主
        $res1 = db('shop') -> alias('s')
                    -> field('s.id shop_id')
                    -> join('admin a','a.id = s.admin_id','LEFT')
                    -> where(['s.user_id' => $user_id,'s.type' => 1,'a.role_id' => 13,'s.status' => 1])
                    -> find();
        if($res1){//是刀圈店主  查看平台的商品
            $check_role['role'] = 3;
            $check_role['msg'] = '是刀圈店主';
        }else{
            //判断用户是否有上级
            $parent_id = db('user_info') -> where('user_id',$user_id) -> value('parent_id');
            if($parent_id > 0){//存在上级 
                //判断其上级是否为刀圈店主
                $res = db('shop') -> alias('s')
                        -> field('s.id shop_id')
                        -> join('admin a','a.id = s.admin_id','LEFT')
                        -> where(['s.user_id' => $parent_id,'s.type' => 1,'a.role_id' => 13,'s.status' => 1])
                        -> find();
                if($res){//上级是刀圈店主
                    $check_role['role'] = 2;
                    $check_role['msg'] = '上级为刀圈店主';
                    $check_role['shop_id'] = $res['shop_id'];
                }else{
                	$ress = db('shop') -> alias('s')
                        -> field('s.id shop_id')
                        -> join('admin a','a.id = s.admin_id','LEFT')
                        -> where(['s.user_id' => $parent_id,'s.type' => 1,'a.role_id' => 12,'s.status' => 1])
                        -> find();
                    if($ress){
                    	$check_role['role'] = 5;//首页提取权限不够   上级是生态圈店主
                    	$check_role['msg'] = '首页提取权限不够';
                    }else{
                    	$check_role['role'] = 4;//首页提取权限不够
                    	$check_role['msg'] = '首页提取权限不够';
                    }
                    
                }

            }else{//不存在上级   查看总平台的商品
                $check_role['role'] = 1;
                $check_role['msg'] = '不存在上级，查看总平台的商品';
            }
        }
        
        
    }else{//未登录
        $check_role['role'] = 0;//首页提取权限不够
        $check_role['msg'] = '首页提取权限不够';
    }
    return json_encode($check_role);
}
/*
.* @ name: 计算佣金
.* @ description: 计算佣金
.* @ param :$order_id【需要计算返佣的订单id】
.* @ return: 返回佣金计算结果
.* @ Author: longdada
.* @ Date: 2019-03-13 09:22:35
.*/  
function saveCost($order_id)
{
	$base=get_conf('base');
	$parent_ratio=$base['data']['parent']/100;
	$parents_ratio=$base['data']['parents']/100;//获取返佣比例
	$where['order_id']=$order_id;
	$where['order_status']=5;
	$where['is_cost']=0;
	if($base['data']['is_retail'] == 1){//如果关闭分销  不进行返佣
		$order_row=db('order')->where($where)->find();
		if(!empty($order_row)){
			$parent_number=$order_row['goods_amount']*$parent_ratio;//计算推荐 人返佣金额
			$parents_number=$order_row['goods_amount']*$parents_ratio;//计算推荐人上级返佣金额
			$info_where['user_id']=$order_row['user_id'];
			$info_row=db('user_info')->where($info_where)->find();
			if(isset($info_row['parent_id'])&&$info_row['parent_id']>0){//有推荐人 给推荐人返佣
				$user_where['id']=$info_row['parent_id'];
				$user_row=db('user')->where($user_where)->find();
				$in_change_data['user_id']=$info_row['parent_id'];
				$in_change_data['type']=1;
				$in_change_data['title']='消费返佣';
				$in_change_data['change_type']=4;
				$in_change_data['money']=$user_row['user_money'];
				$in_change_data['next_money']=$user_row['user_money']+ $parent_number;
				$in_change_data['change_money']= $parent_number;
				$in_change_data['acc_type']= 1;
				$in_change_data['account']= $order_row['user_id'];
				$in_change_data['remark']= '推荐的用户消费获取返佣'.$parent_number;
				$in_change_data['status']= 1;
				$in_change_data['add_time']= time();
				$in_change_data['update_time']= time();
				db('user_change')->insert($in_change_data);
				$up_user_data['id']=$info_row['parent_id'];
				$up_user_data['user_money']= $in_change_data['next_money'];
				db('user')->update($up_user_data);
				$parent_info_where['user_id']=$info_row['parent_id'];
				$parent_info_row=db('user_info')->where($parent_info_where)->find();
				if($parent_info_row['parent_id']>0){//如果推荐人也有上级 给上级返佣
					$parent_user_where['id']=$parent_info_row['parent_id'];
					$parent_user_row=db('user')->where($parent_user_where)->find();
					$in_parent_change_data['user_id']=$parent_info_row['parent_id'];
					$in_parent_change_data['type']=1;
					$in_parent_change_data['title']='消费返佣';
					$in_parent_change_data['change_type']=4;
					$in_parent_change_data['money']=$parent_user_row['user_money'];
					$in_parent_change_data['next_money']=$parent_user_row['user_money']+ $parents_number;
					$in_parent_change_data['change_money']= $parents_number;
					$in_parent_change_data['acc_type']= 2;
					$in_parent_change_data['account']= $order_row['user_id'];
					$in_parent_change_data['remark']= '推荐用户的下级用户消费获取返佣'.$parents_number;
					$in_parent_change_data['status']= 1;
					$in_change_data['add_time']= time();
					$in_change_data['update_time']= time();
					db('user_change')->insert($in_parent_change_data);
					$up_parent_user_data['id']=$parent_user_row['id'];
					$up_parent_user_data['user_money']= $in_parent_change_data['next_money'];
					db('user')->update($up_parent_user_data);
				}
				$up_order_data['order_id']=$order_id;
				$up_order_data['is_cost']=1;
				db('order')->update($up_order_data);
			}
			$rs_arr['code']=1;
		}else{
			$rs_arr['code']=0;
		}
		return $rs_arr;
	}
	
}  
//
/*
.* @ name: banner图商品提成管理
.* @ description: 计算提成金额
.* @ param :$order_id【需要计算返佣的订单id】
.* @ return: 返回提成计算结果
.* @ Author: 冲哥Carry
.* @ Date: 2019-03-13 09:22:35
.*/  
function rebateCost($order_id){
	//查询该订单下  从banner购买的商品
	$goods_list = db('order_goods') -> field('goods_price,attr_price,goods_name,goods_id,goods_number') -> where(['order_id' => $order_id,'rebate' => 'rebate']) -> select();
	$user_id = db('order') -> where(['order_id' => $order_id]) -> value('user_id');
	$info_row=db('user_info')->where(['user_id' => $user_id])->find();
	if(isset($info_row['parent_id'])&&$info_row['parent_id']>0){//有推荐人 给推荐人返佣
		if(!empty($goods_list)){
			
			foreach ($goods_list as $key => $value) {
				$rebate = db('media') -> where(['jump_id' => $value['goods_id'],'type'=>1]) -> value('rebate');//每件提成比例
				$parent_number = $rebate*$value['goods_number'];
				$user_where['id']=$info_row['parent_id'];
				$user_row=db('user')->where($user_where)->find();
				$in_change_data['user_id']=$info_row['parent_id'];
				$in_change_data['type']=1;
				$in_change_data['title']='消费返佣';
				$in_change_data['change_type']=4;
				$in_change_data['money']=$user_row['user_money'];
				$in_change_data['next_money']=$user_row['user_money']+ $parent_number;
				$in_change_data['change_money']= $parent_number;
				$in_change_data['acc_type']= 1;
				$in_change_data['account']= $user_id;
				$in_change_data['remark']= '推荐的用户消费获取返佣'.$parent_number.'元';
				$in_change_data['status']= 1;
				$in_change_data['add_time']= time();
				$in_change_data['update_time']= time();
				db('user_change')->insert($in_change_data);
				$up_user_data['id']=$info_row['parent_id'];
				$up_user_data['user_money']= $in_change_data['next_money'];
				db('user')->update($up_user_data);
			}
		}
	}
	
}
/*
.* @ name: 商品返积分
.* @ description: 商品返积分
.* @ param :$order_id【需要计算返佣的订单id】
.* @ return: 商品返积分
.* @ Author: 冲哥Carry
.* @ Date: 2019-03-20 09:22:35
.*/  
function rebatePoints($order_id){
	$base=get_conf('base');
	$rebate_points = $base['data']['integral_ratio'];
	$order_info = db('order') -> where(['order_id' => $order_id]) -> find();
	// if($order_info){
	// 	$parent_number = round(($order_info['order_amount'] / $rebate_points),0);
	// 	$user_where['id']=$order_info['user_id'];
	// 	$user_row=db('user')->where($user_where)->find();
	// 	$in_change_data['user_id']=$order_info['user_id'];
	// 	$in_change_data['type']=2;
	// 	$in_change_data['title']='消费返积分'.$order_info['order_sn'].'订单消费'.$order_info['order_amount'].'元';
	// 	$in_change_data['change_type']=4;
	// 	$in_change_data['money']=$user_row['score'];
	// 	$in_change_data['next_money']=$user_row['score']+ $parent_number;
	// 	$in_change_data['change_money']= $parent_number;
	// 	$in_change_data['acc_type']= 1;
	// 	$in_change_data['account']= $order_info['user_id'];
	// 	$in_change_data['remark']= '用户消费获取积分'.$parent_number;
	// 	$in_change_data['status']= 1;
	// 	$in_change_data['add_time']= time();
	// 	$in_change_data['update_time']= time();
	// 	db('user_change')->insert($in_change_data);
	// 	$up_user_data['id']=$order_info['user_id'];
	// 	$up_user_data['score']= $in_change_data['next_money'];
	// 	db('user')->update($up_user_data);

	// }
}
/*
.* @ name: 审核结果通知用户
.* @ description: 审核结果通知用户
.* @ param :$id   店铺id
.* @ return: 审核结果通知用户
.* @ Author: 冲哥Carry
.* @ Date: 2019-04-19 09:22:35
.*/  
function send_shop_msg($id){
	//获取店铺信息
	$shop_info = db('shop') -> field('type,shop_name,mobile,status') -> where(['id' => $id]) -> find();
	if($shop_info){
		$shop_type = $shop_info['type'] == 1 ? '刀圈店铺' : '生态圈店铺';		
		$shop_status = $shop_info['status'] == 1 ? '审核通过' : '审核被拒';
		//模拟数据
		$aa = $shop_type.$shop_status.$shop_info['mobile'];
		db('shop') -> where(['id' => $id]) -> update(array('synopsis' => $aa));
	}
}
/*
.* @ name: 审核用户是否满足申请生态圈条件
.* @ description: 审核用户是否满足申请生态圈条件
.* @ param :$user_id   用户ID
.* @ return: 审核用户是否满足申请生态圈条件返回前端
.* @ Author: 冲哥Carry
.* @ Date: 2019-04-20 08:50:35
.*/ 
function check_stq_user_role($user_id){
	//累计消费3000元  ---------------会员所有已完成的订单金额是否超过3000元
	$all_amount = db('order') -> where(['pay_status' => 1,'order_status' => 5,'user_id' => $user_id]) -> value('ifnull(SUM(order_amount),0)');

	//一次性在生态圈购买1888元 ----------------会员一次性在生态圈购买订单金额超过1888元
	$one_amount = db('order') -> where(['pay_status' => 1,'order_status' => 5,'user_id' => $user_id,'type' => 2]) -> where('order_amount >= 1888') -> value('IFNULL(order_amount,0)');

	//成功推荐新用户8个 -----------------会员推荐的新用户超过8个
	$recommend_num = db('user_info') -> where(['parent_id' => $user_id]) -> count();

	if($all_amount >= 3000 || $one_amount >= 1888 || $recommend_num >= 8){
		$check_stq_user_role['stq_user_role'] = 1;
		$check_stq_user_role['stq_condition'] = '您已经取得申请成为生态圈店主的资格,请前往提交审核资料,若已经申请请忽略本提示!';
	}else{
		$check_stq_user_role['stq_user_role'] = 0;
		$check_stq_user_role['stq_condition'] = '您已经是生态圈店主';
	}
	return $check_stq_user_role;

}
/*
.* @ name: 验证收假后是否唯一
.* @ description:  验证收假后是否唯一
.* @ param :$user_id   用户ID
.* @ return:  验证收假后是否唯一
.* @ Author: 冲哥Carry
.* @ Date: 2019-04-20 08:50:35
.*/ 
function check_phone($phone){
	$res = db('user') -> where(['user_login' => $phone]) -> value('id');
	return $res;
}
/*
.* @ name: 未读消息数
.* @ description:  验证收假后是否唯一
.* @ param :$user_id   用户ID
.* @ return:  验证收假后是否唯一
.* @ Author: 冲哥Carry
.* @ Date: 2019-04-20 08:50:35
.*/ 
function unread_msg($user_id){
	$num = 0;
    $xt_num = db('msg')->alias('m')->join('user_msg um','m.id=um.msg_id','left')->where(['um.user_id'=>$user_id,'m.type'=>0,'m.status'=>1,'um.status'=>0])->count();
    $my_num = db('msg')->alias('m')->join('user_msg um','m.id=um.msg_id','left')->where(['um.user_id'=>$user_id,'m.type'=>1,'um.status'=>0])->count();
  
    //查询对话列表
    $list = db('chat_list')->where("user_id",$user_id)->whereor('to_user_id',$user_id)->limit(20)->order('add_time desc')->select();
    if($list){
      foreach ($list as $k => $v) {
        if($v['user_id']==$user_id){
          $id = $v['to_user_id'];
        }else{
          $id = $v['user_id'];
        }
        $num += db("chat")->where("to_user_id=$user_id and user_id=$id and status=0")->count();
      }  
    }  
    $nums =  $xt_num +  $my_num + $num;
    $nums ? $nums : 0;
    return $nums;
}
//random() 函数返回随机整数。
function random($length = 6 , $numeric = 0) {
        PHP_VERSION < '4.2.0' && mt_srand((double)microtime() * 1000000);
        if($numeric) {
            $hash = sprintf('%0'.$length.'d', mt_rand(0, pow(10, $length) - 1));
        } else {
            $hash = '';
            $chars = 'ABCDEFGHJKLMNPQRSTUVWXYZ23456789abcdefghjkmnpqrstuvwxyz';
            $max = strlen($chars) - 1;
            for($i = 0; $i < $length; $i++) {
                $hash .= $chars[mt_rand(0, $max)];
            }
        }
        return $hash;
    }
/*
.* @ name: 生成用户唯一token
.* @ description:  生成用户唯一token
.* @ param :$user_id   用户ID
.* @ return:  生成用户唯一token
.* @ Author: 冲哥Carry
.* @ Date: 2019-07-25 08:50:35
.*/ 
//获取用户token
// function getToken($user_id){
// 	$token = sha1(random(8));
// 	if( $token ==false ){
//         $arr['code'] = 0;
//         $arr['msg'] = 'user_token获取失败';
//     }
//     $info = array(
//     			'token' => $token,
//     			'user_id' => $user_id
//     		);
//     $sign = \think\Cache::set('dddddddd',$info,60*60*2);
    
//     if($sign == false){
//     	$arr['code'] = 0;
//         $arr['msg'] = 'user_token获取失败';
//     }else{
//     	$arr['code'] = 1;
//         $arr['user_token'] = $token;
//     }
//     return $arr['user_token'];
// }
// function check_user(){
// 	$token = get_user_token();
// 	echo $token;
// 	$infos = \think\Cache::get('dddddddd');
// 	halt($infos);die;
// }
/*

.* @ name: 检测用户唯一token
.* @ description:  生成用户唯一token
.* @ param :$user_id   用户ID
.* @ return:  生成用户唯一token
.* @ Author: 冲哥Carry
.* @ Date: 2019-07-25 08:50:35
.*/ 
// function check_user_token(){

//         Vendor('firebase.phpjwt.src.JWT');
//         $user_token = get_user_token();  //上一步中返回给用户的token
//         echo $user_token;die;

//         $key = "chonggeCarry";  //上一个方法中的 $key 本应该配置在 config文件中的
//         $jwt = new \JWT();

//         $info = $jwt -> decode($user_token,$key,["HS256"]); //解密jwt
//         halt($info);die;
//         $info = json_decode($info);
//         if($info->code == 2){
//             $arr['code'] = $info->code;
//             $arr['msg'] = $info->msg;
//         }else{
//             $arr['code'] = 1;
//             $arr['uid'] = $info->msg->uid;
//         }
//         return json($arr);
//     }

function get_cur_user_id(){
	$user_token=request()->header('USER-TOKEN');;

	if(empty($user_token)){
		$user_id=0;
	}else{
		$base_user_token=db('user_token') -> where(['user_token' => $user_token]) -> value('user_id');
		if(empty($base_user_token)){
			$user_id=0;
		}else{
			$user_id=$base_user_token;
		}
	}
	return $user_id;
}
